<template>
	<transition name="dialog-fade">
		<div class="at-dialog-box" v-show="visible" @click.self="handleWrapperClick">
			<div class="at-dialog" :class="[sizeClass, customClass]" ref="dialog" :style="style">
				<div class="at-dialog__header">
					<slot name="title">
						<span class="at-dialog__title">{{title}}</span>
					</slot>
					<button type="button" class="at-dialog__headerbtn" aria-label="Close" v-if="showClose"  @click="handleClose">
						<img src="../../theme-default/assets/dialog/close.png" class='at-dialog__close'>
					</button>
				</div>
				<div class="at-dialog__body" v-if="rendered">
					<slot></slot>
				</div>
				<div class="at-dialog__footer" v-if="$slots.footer">
					<slot name="footer"></slot>
				</div>
			</div>
		</div>
	</transition>
</template>

<script>
import Popup from '../../common/utils/popup';
import emitter from '../../common/mixins/emitter';

export default {
	name: 'at-dialog',

	mixins: [Popup, emitter],

	props: {
		// Dialog 的标题
		title: {
			type: String,
			default: ''
		},
		// 是否需要遮罩层
		modal: {
			type: Boolean,
			default: true
		},
		// 遮罩层是否插入至 body 元素上，若为 false，则遮罩层会插入至 Dialog 的父元素上
		modalAppendToBody: {
			type: Boolean,
			default: true
		},
		// 是否在 Dialog 出现时将 body 滚动锁定
		lockScroll: {
			type: Boolean,
			default: true
		},
		// 是否可以通过点击 modal 关闭 Dialog
		closeOnClickModal: {
			type: Boolean,
			default: true
		},
		// 是否可以通过按下 ESC 关闭 Dialog
		closeOnPressEscape: {
			type: Boolean,
			default: true
		},
		// 是否显示关闭按钮
		showClose: {
			type: Boolean,
			default: true
		},
		// Dialog 的大小
		size: {
			type: String,
			default: 'small'
		},
		// Dialog 的自定义类名
		customClass: {
			type: String,
			default: ''
		},
		// Dialog CSS 中的 top 值（仅在 size 不为 full 时有效）
		top: {
			type: String,
			default: '15%'
		},
		// 关闭前的回调，会暂停 Dialog 的关闭
		beforeClose: Function
	},

	watch: {
		visible(val) {
			this.$emit('update:visible', val);
			if (val) {
				this.$emit('open');
				this.$el.addEventListener('scroll', this.updatePopper);
				this.$nextTick(() => {
					this.$refs.dialog.scrollTop = 0;
				});
			} else {
				this.$el.removeEventListener('scroll', this.updatePopper);
				this.$emit('close');
			}
		}
	},

	computed: {
		sizeClass() {
			return `at-dialog--${this.size}`;
		},
		style() {
			return this.size === 'full' ? {} : { 'top': this.top };
		}
	},

	methods: {
		handleWrapperClick() {
			if (!this.closeOnClickModal) return;
			this.handleClose();
		},
		handleClose() {
			if (typeof this.beforeClose === 'function') {
				this.beforeClose(this.hide);
			} else {
				this.hide();
			}
		},
		hide(cancel) {
			if (cancel !== false) {
				this.$emit('update:visible', false);
				this.$emit('visible-change', false);
			}
		},
		updatePopper() {
			this.broadcast('ElSelectDropdown', 'updatePopper');
			this.broadcast('ElDropdownMenu', 'updatePopper');
		}
	},

	mounted() {
		if (this.visible) {
			this.rendered = true;
			this.open();
		}
	}
};
</script>
